 
import json
from flask import Flask, session, redirect, url_for, escape,  jsonify
from .db import mssql
#from .modbustcp import modbustcp_
#from .modbustcp import modbusSys_
from .modbustcp import modbus
class TRouter:
    def __init__(self) -> None:
        self.handlers={}
    def register(self , category, method , func):
        key = category + '/'+ method
        self.handlers[key] = func
    def callHandler(self , handlerKey , request , result):
        try:
            flag = handlerKey in self.handlers.keys() 
            if (flag):
                try:
                    func = self.handlers[handlerKey]
                    func(request , result)
                except Exception as eer:
                    print(eer)
            else:
                result["status"] = -1
                result["error"] = "router("+handlerKey+") is error."
        except Exception as er:
            print(er)
    def getRequestParams(self, request): 
        params = {}
        try:
            if request.data!='':
                try:
                    params = json.loads(request.data)
                except Exception as erJson:
                    print(erJson)
            
            try:
                ps = request.args
                for key in ps.keys():
                    params[key] = ps[key]
            except Exception as e0:
                print(e0)
            try:
                ps = request.form
                for key in ps.keys():
                    params[key] = ps[key]
            except Exception as e1:
                print(e1) 
        except Exception as error:
            print(error)
        return  params
    def callApi(self, result, request):
        print(result)
        try:
            handlerKey = result["category"] + "/" + result["method"]
            if handlerKey in self.handlers.keys() :
                handler = self.handlers[handlerKey]
                handler(result , request , self)
        except Exception as er:
            print(er)

router = TRouter()
router.register("mssql", "query", mssql.mssql.routerHandlerQuery)
router.register("modbus", "start", modbus.mb.routerHandlerStart)
router.register("modbus", "getVars", modbus.mb.routerHandlerGetVars)
router.register("modbus", "getDevVars", modbus.mb.routerHandlerGetDevVars)
#router.register("modbus", "startClients", modbustcp_.modbusTcp.routerHandlerStartClients)
#router.register("modbus", "getRegisters", modbustcp_.modbusTcp.routerHandlerGetRegisters)


#router.register("modbusSys", "start", modbusSys_.sys.routerHandlerStart)
#router.register("modbusSys", "getRegisters", modbusSys_.sys.routerHandlerGetRegisters)
